package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 定时任务类（处理超时未支付或者一直派送中的订单）
 */
@Slf4j
@Component

public class OrderTask {
    @Autowired
    private OrdersMapper ordersMapper;
    /**
     * 处理订单超时未支付订单，每分钟执行一次（下单订单后，如果15分钟内未支付，则取消订单）
     */
    @Scheduled(cron = "0 * * * * ?")//每分钟执行一次
    public void processTimeoutOrders(){
        log.info("处理超时订单");
        LocalDateTime orderTimeout = LocalDateTime.now().minusMinutes(15);
        List<Orders> ordersList = ordersMapper.selectByStatusAndOrderTime(Orders.PENDING_PAYMENT,orderTimeout);
        if (ordersList != null && ordersList.size() > 0){
            for (Orders orders : ordersList) {
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelReason("订单超时，自动取消");
                orders.setCancelTime(LocalDateTime.now());
                ordersMapper.update(orders);
            }
        }
    }

    /**
     * 处理订单派送中订单，每分钟执行一次（每天凌晨一点检查一次是否存在派送中订单，有则自动完成订单）
     */
    @Scheduled(cron = "0 0 1 * * ?")//每天凌晨一点执行一次
    public void processDeliveryOrders(){
        log.info("处理派送中订单");
        LocalDateTime deliveryTime = LocalDateTime.now().minusHours(1);
        List<Orders> ordersList = ordersMapper.selectByStatusAndOrderTime(Orders.DELIVERY_IN_PROGRESS,deliveryTime);
        if (ordersList != null && ordersList.size() > 0){
            for (Orders orders : ordersList) {
                orders.setStatus(Orders.COMPLETED);
                orders.setDeliveryTime(LocalDateTime.now());
            }
        }
    }
}
